package com.gitee.liuzhi.demo.juc;

import java.util.concurrent.TimeUnit;

/**
 * @Author liuzhi
 * @Date 2023/9/6 20:41
 * @Version 1.0
 * @Description volatile解决多线程访问共享变量可见性问题
 */
public class VolatileDemo {

    public static void main(String[] args) throws InterruptedException {
        VolatileDemo sample = new VolatileDemo();
        Thread threadA = new Thread(sample::refresh, "threadA");
        Thread threadB = new Thread(sample::load, "threadB");
        threadB.start();
        TimeUnit.SECONDS.sleep(5);
        threadA.start();
    }

    /**
     * 多线程修改共享变量使用volatile修饰保证可见性
     */
    private volatile boolean flag = false;

    public void refresh() {
        this.flag = true;
        String threadName = Thread.currentThread().getName();
        System.out.println("线程: " + threadName + " :修改共享变量flag");
    }

    public void load() {
        String threadName = Thread.currentThread().getName();
        while (!flag) {
        }
        System.out.println("线程: " + threadName + " :当前线程嗅探到flag的状态改变");
    }

}
